package top.api.service;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.api.common.RedisKey;
import top.api.common.ResUlt;
import top.api.domain.dto.LoginDto;
import top.api.domain.entity.User;
import top.api.enums.CommonStatusEnum;
import top.api.enums.DeviceTypeEnums;
import top.api.mapper.UserMapper;
import top.api.utils.BeanCopyUtils;
import top.api.utils.RedisCache;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class LoginServiceImpl {
    private final RedisCache redisCache;
    private final UserMapper userMapper;

    public ResUlt<?> h5Login(LoginDto loginDto){
        // 查询验证码是否正确, 无论正确错误都把验证码删除
        String cachePicCode = redisCache.getCacheObject(RedisKey.getPicCodeKey() + ":" + loginDto.getUuid());
        if (!Objects.equals(cachePicCode,loginDto.getPicCode())) {
            redisCache.deleteObject(RedisKey.getPicCodeKey() + ":" + loginDto.getUuid());
            return ResUlt.error("图片验证码错误!");
        }

        redisCache.deleteObject(RedisKey.getPicCodeKey() + ":" + loginDto.getUuid());

        // 查询账号信息是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,loginDto.getUserName());
        queryWrapper.eq(User::getPassword,loginDto.getPassword());

        User dbUser = userMapper.selectOne(queryWrapper);

//        if (ObjectUtils.isEmpty(dbUser) || ! BCrypt.checkpw(loginDto.getPassword(), dbUser.getPassword())){
//            return ResUlt.error("账号或密码错误!");
//        }

        if (ObjectUtils.isEmpty(dbUser)){
            return ResUlt.error("账号或密码错误!");
        }

        // 查询是否被冻结
        if (CommonStatusEnum.error.equals(dbUser.getStatus())){
            return ResUlt.error("账号异常!");
        }

        SaLoginModel model = new SaLoginModel();
        model.setDevice(DeviceTypeEnums.H5.toString());

        StpUtil.login(dbUser.getId(),model);

        log.warn("用户登录: [{}]",dbUser);

        return ResUlt.success("success", StpUtil.getTokenValue());
    }

    public ResUlt<?> logOut() {
        try{
            StpUtil.logout(StpUtil.getLoginIdAsInt(),DeviceTypeEnums.H5.toString());
        }catch (Exception e){
            return ResUlt.success("退出成功");
        }
        return ResUlt.success("退出成功");
    }

    public ResUlt<?> checkLogin() {
       return ResUlt.success(StpUtil.isLogin());
    }
}
